package leetcode.weekly.week318;

//Solution2Test
public class Solution2 {

	int N = (int) 1e5 + 1;

	public long maximumSubarraySum(int[] nums, int k) {
		int[] hash = new int[N];
		int kind = 0;
		int p = 0;
		long sum = 0, ans = 0;
		while (p < k) {
			int num = nums[p];
			if (hash[num] == 0) {
				kind += 1;
			}
			hash[num]++;
			sum += num;
			p++;
		}
		if (kind == k) {
			ans = sum;
		}
		while (p < nums.length) {
			int r = nums[p];
			int l = nums[p - k];
			if (hash[r] == 0) {
				kind++;
			}
			hash[r]++;
			hash[l]--;
			sum += r;
			sum -= l;
			if (hash[l] == 0) {
				kind--;
			}
			if (kind == k) {
				ans = Math.max(ans, sum);
			}
			p++;
		}
		return ans;
	}

}
